<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Associations_model extends CI_Model {

    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
    }
    
    function get_all()
    {
        $query = $this->db->get('associations');
        return $query->result();
    }
    
    function get_all_location()
    {
        $query = $this->db->get_where('associations', array('valid' => 1));
        $locations = array();
        foreach ($query->result() as $row)
		{
			$location["lat"] = $row->location_lat;
			$location["lng"] = $row->location_lng;
			$location["data"]["id"] = $row->id;
			$location["data"]["raison_social"] = $row->raison_social;
			$location["data"]["sigle"] = $row->sigle;
			$location["data"]["adresse"] = $row->adresse;
			$location["data"]["telephone"] = $row->telephone;
			$location["data"]["mail"] = $row->mail;
			$location["data"]["fondateur"] = $row->fondateur;
			$location["data"]["date_fondation"] = $row->date_fondation;
			$location["data"]["contact"] = $row->contact;
			$location["data"]["description"] = $row->description;
			$locations[] = $location;
		}
        return $locations;
    }
    
    function get_all_valid()
    {
        $query = $this->db->get_where('associations', array('valid' => 1));
        return $query->result();
    }

    function insert($record)
    {
		$this->db->insert('associations', $record);
		return $this->db->insert_id();
    }


    function update($id, $record)
    {
        return $this->db->update('associations', $record, array('id' => $id));
    }
    
    function remove($id)
    {
        return $this->db->delete('associations', array('id' => $id));
    }
    
    function exist_id($id){
		$query = $this->db->get_where('associations', array('id' => $id));
		return $query->num_rows() > 0;
	}
	
	function exist_name($name){
		$query = $this->db->get_where('associations', array('raison_social' => $name));
		return $query->num_rows() > 0;
	}
	
	function get_name($name){
		$query = $this->db->get_where('associations', array('raison_social' => $name));
		if($query->num_rows() == 1)
			return $query->row_array();
		else
			return false;
	}
	
	function get_id($id){
		$query = $this->db->get_where('associations', array('id' => $id));
		if($query->num_rows() == 1)
			return $query->row_array();
		else
			return false;
	}
    
    function exist_email($email){
		$query = $this->db->get_where('associations', array('email' => $email));
		return $query->num_rows() > 0;
	}
	
    function add_user($associationID, $userID, $role)
    {
	     	
        $data = array( 'user_id' => $userID, 
        				'association_id' => $associationID,  
        				'role' => $role,
        				'valid' => 0,  
        				);
        return $this->db->insert('users_associations', $data);
    }

}